<template> 
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <!-- <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button> -->
      </div>
      <div style="display: flex;align-items: center;">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="输入搜索：" style="margin: 0 10px 0 0;">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="角色名称" clearable></el-input>
          </el-form-item>
        </el-form>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <!-- <i class="el-icon-tickets"></i>
      <span>数据列表</span> -->
      <el-button size="mini" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加角色</el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="roleTable"
                :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>

        <el-table-column label="角色名称" align="center">
          <template slot-scope="scope">
            <!-- {{scope.row.name}} -->
            <div v-html="hightLight(listQuery.keyword, scope.row.name)"></div>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template slot-scope="scope">{{scope.row.description}}</template>
        </el-table-column>
        <el-table-column label="用户数"  width="200" align="center">
          <template slot-scope="scope">{{scope.row.adminCount}}</template>
        </el-table-column>
        <el-table-column label="添加时间" width="260" align="center">
          <template slot-scope="scope">{{scope.row.createTime | formatDateTime}}</template>
        </el-table-column>
        <el-table-column label="是否启用" width="240" align="center">
          <template slot-scope="scope">
            {{scope.row.status ? '是' : '否'}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" align="center">
          <template slot-scope="scope">
            <el-row>
            <el-button size="mini"
                       type="text"

                       @click="handleUpdate(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button size="mini"
                       type="text"
                       v-if="scope.row.id !== 1"
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="'添加/管理角色'"
      :visible.sync="dialogVisible"
      width="60%">
      <el-form :model="role"
              :rules="rules"
               ref="roleForm"
               label-width="150px" size="small">
        <el-form-item label="角色名称：" prop="name">
          <el-input v-model="role.name" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="role.description" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="是否启用：" prop="status">
          <el-radio-group v-model="role.status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分配菜单与资源：" prop="menuIds">
          <el-tree
            :data="treeList"
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :default-checked-keys="checkedTree"
            :props="defaultProps">
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm('roleForm')" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {fetchList,createRole,updateRole,updateStatus,deleteRole} from '@/api/role';
  import {formatDate} from '@/utils/date';
  import { getResourceTree, getDetailTree, roleCreate, roleUpdate, fetchAllResourceList } from '@/api/app';

  const defaultListQuery = {
    pageNum: 1,
    pageSize: 10,
    keyword: null
  };
  const defaultRole = {
    id: null,
    name: null,
    description: null,
    supAdminYn: null,
    status: null,
    menuIds: [],
    resourceIds: [],

  };
  export default {
    name: 'roleList',
    data() {
      return {
        rules: {
          name: [
              { required: true, message: '请填写角色名称' }
          ],
          status: [
              { required: true, message: '请选择是否启用' }
          ],
          menuIds: [
              { required: true, message: '请选择菜单资源' }
          ],
        },
        listQuery: Object.assign({}, defaultListQuery),
        list: null,
        total: null,
        listLoading: false,
        dialogVisible: false,
        role: Object.assign({}, defaultRole),
        isEdit: false,
        treeList: [],
        defaultProps: {
          children: 'children',
          label: 'title'
        },
        checkedTree: [],
        btnMenu: {
          edit: true,
          delete: true,
        },
      }
    },
    created() {
      const menu = JSON.parse(localStorage.getItem('listMenu'));
      const item = menu.filter(item => item.title === '角色管理')[0];
      fetchAllResourceList({menuId: item.id }).then(res => {
        res.data.forEach(dom => {
          if (dom.component === '' && dom.name === '后台角色管理') {
            this.btnMenu.edit = false;
          }
          if (dom.component === '' && dom.name === '后台角色删除') {
            this.btnMenu.delete = false;
          }
        });
      });
      this.getList();
      this.getTree();
    },
    filters: {
      formatDateTime(time) {
        if (time == null || time === '') {
          return '-';
        }
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    methods: {
      hightLight (keyWord, suggtion) {
            // 使用 regexp 构造函数，因为这里要匹配的是一个变量
            let newSrt = null;
            const reg = new RegExp(keyWord, 'ig')
            if (keyWord && suggtion) {
                newSrt = String(suggtion).replace(reg, function (p) {
                    return '<span style="color: #409EFF">' + p + '</span>'
                })
            } else {
                newSrt = suggtion;
            }
            return newSrt
        },
      getTree() {
        getResourceTree().then(res => {
          // console.log(res);
          this.treeList = this.dealTree(res.data);
          // this.test(this.treeList);
        });
      },
      dealTree(list) {
        list.forEach(item => {
          if (item.children.length > 0) {
            item.children.forEach(child => {
              if (child.children.length > 0) {
                child.children.forEach(sol => {
                  if (sol.children.length > 0) {

                  } else if (sol.children.length === 0 && sol.resourceList.length > 0) {
                    sol.children = sol.resourceList;
                  }
                })
              } else if (child.children.length === 0 && child.resourceList.length > 0) {
                child.children = child.resourceList;
              }
            });
          }
        })
        return list;
      },
      renderContent(h, { node, data, store }) {
        console.log(data);
        if (data.resourceList) {
          if (data.resourceList.length > 0) {
            return (
              <span class="custom-tree-node">
                <span>{node.label}</span>
                <div>
                  <div>
                    <input type="checkbox" name="interests" value="sports"/>
                  </div>
                  <div>
                    <div >1111</div>
                  </div>
                </div>
              </span>);
          } else {
            return (
              <span class="custom-tree-node">
                <span>{node.label}</span>

              </span>);
          }
        } else {
          return (
              <span class="custom-tree-node">
                <span>{node.label}</span>

              </span>)
        }
      },
      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
        this.getList();
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      handleAdd() {
        this.getTree();
        this.checkedTree = [];
        this.dialogVisible = true;
        this.isEdit = false;
        this.role = Object.assign({},defaultRole);
        // console.log(this.checkedTree, this.role);
      },
      handleStatusChange(index, row) {
        this.$confirm('是否要修改该状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStatus(row.id, {status: row.status}).then(response => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消修改'
          });
          this.getList();
        });
      },
      handleDelete(index, row) {
        if (this.btnMenu.delete) {
          this.$confirm('删除后该角色下的用户角色都会被清除，你还要继续吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids = [];
            ids.push(row.id);
            let params=new URLSearchParams();
            params.append("ids",ids);
            deleteRole(params).then(response => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList();
            });
          });
        } else {
          this.$message({
            type: 'error',
            message: '无权限操作'
          });
        }
      },
      handleUpdate(index, row) {
        if (this.btnMenu.edit) {
          this.dialogVisible = true;
          this.isEdit = true;
          getDetailTree(row.id).then(res => {
            this.dealRecoverTree(res.data.tree);
            this.role.id = res.data.id;
            this.role.name = res.data.name;
            this.role.description = res.data.description;
            this.role.supAdminYn = res.data.supAdminYn;
            this.role.status = res.data.status ? 1 : 0;
          });
        } else {
          this.$message({
            type: 'error',
            message: '无权限操作'
          });
        }
      },
      dealRecoverTree(list) {
        let menu = [];
        let resource = [];
        list.forEach(item => {
          if (item.check) {
            item.children.forEach(first => {
              if (first.check) {
                if (first.children.length > 0) {
                  first.children.forEach(two => {
                    if (two.check) {
                      if (two.resourceList.length > 0) {
                        const a = two.resourceList.every(obj => obj.check);
                        if (a) {
                          menu.push(two.id);
                        };
                        two.resourceList.forEach(dom1 => {
                          if (dom1.check) {
                            resource.push(dom1.id)
                          }
                        })
                      } else {
                        menu.push(two.id);
                      }
                    }
                  })
                } else {
                  if (first.resourceList.length > 0) {
                    const b = first.resourceList.every(obj => obj.check);
                    if (b) {
                      menu.push(first.id);
                    };
                    first.resourceList.forEach(dom => {
                      if (dom.check) {
                        resource.push(dom.id)
                      }
                    })
                  } else {
                    menu.push(first.id);
                  }
                }
              }
            })
          }
        });
        // console.log(menu, resource);
        this.checkedTree = menu.concat(resource);
      },
      handleDialogConfirm(formName) {
        const all = this.$refs.tree.getCheckedNodes();
        const half = this.$refs.tree.getHalfCheckedNodes();
        if (all.length > 0) {
          all.forEach(item => {
            if (item.title === item.name) {
              this.role.resourceIds.push(item.id);
            } else {
              this.role.menuIds.push(item.id);
            }
          });
        }
        if (half.length > 0) {
          half.forEach(item => {
            if (item.title === item.name) {
              this.role.resourceIds.push(item.id);
            } else {
              this.role.menuIds.push(item.id);
            }
          });
        }
        console.log(this.role);
        this.$refs[formName].validate((valid) => {
            if (valid) {
                if (this.isEdit) {
                  roleUpdate(this.role).then(res => {
                    this.$message({
                      type: 'success',
                      message: '修改成功!'
                    });
                    this.dialogVisible = false;
                    this.getList();
                  });
                } else {
                  roleCreate(this.role).then(res => {
                    this.$message({
                      type: 'success',
                      message: '操作成功!'
                    });
                    this.dialogVisible = false;
                    this.getList();
                  })
                }
            } else {
                return false;
            }
        });
      },
      handleSelectMenu(index,row){
        // this.$router.push({path:'/ums/allocMenu',query:{roleId:row.id}})
        this.$router.push({path:'/play/allocPlayMenu',query:{roleId:row.id}})
      },
      handleSelectResource(index,row){
        // this.$router.push({path:'/ums/allocResource',query:{roleId:row.id}})
        this.$router.push({path:'/play/allocPlayResource',query:{roleId:row.id}})
      },
      getList() {
        this.listLoading = true;
        fetchList(this.listQuery).then(response => {
          this.listLoading = false;
          this.list = response.data.list;
          this.total = response.data.total;
        });
      }
    }
  }
</script>
<style></style>


